
package com.jf.cloud.api.order.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.jf.cloud.api.coupon.dto.LockCouponDTO;
import com.jf.cloud.api.coupon.feign.CouponOrderFeignClient;
import com.jf.cloud.api.feign.SearchSpuFeignClient;
import com.jf.cloud.api.leaf.dto.SegmentDTO;
import com.jf.cloud.api.leaf.dto.SegmentItemDTO;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.api.order.constant.ShopCityStatus;
import com.jf.cloud.api.product.dto.SkuStockLockDTO;
import com.jf.cloud.api.product.feign.SkuStockLockFeignClient;
import com.jf.cloud.api.product.feign.SpuFeignClient;
import com.jf.cloud.api.user.dto.UserScoreLockDTO;
import com.jf.cloud.api.user.feign.UserScoreLockFeignClient;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.constant.OrderCacheNames;
import com.jf.cloud.common.cache.util.CacheManagerUtil;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.constant.OrderType;
import com.jf.cloud.common.order.constant.ShopCartItemDiscountType;
import com.jf.cloud.common.order.dto.*;
import com.jf.cloud.common.order.util.OrderLangUtil;
import com.jf.cloud.common.order.vo.*;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.product.constant.ShopCartSpuActivityType;
import com.jf.cloud.common.product.vo.GiveawaySpuVO;
import com.jf.cloud.common.product.vo.GiveawayVO;
import com.jf.cloud.common.product.vo.SpuVO;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.common.response.ServerResponseEntity;
import ma.glasnost.orika.MapperFacade;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 提交订单适配
 * @author zz
 * @date 2020/12/07
 */
@Component
public class SubmitOrderManager {
    private static final Logger logger = LoggerFactory.getLogger(SubmitOrderManager.class);


    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private SegmentFeignClient segmentFeignClient;

    @Autowired
    private SkuStockLockFeignClient skuStockLockFeignClient;

    @Autowired
    private CouponOrderFeignClient couponOrderFeignClient;

    @Autowired
    private UserScoreLockFeignClient userScoreLockFeignClient;

    @Autowired
    private SpuFeignClient spuFeignClient;

    @Autowired
    private SearchSpuFeignClient searchSpuFeignClient;

    public ServerResponseEntity<ShopCartOrderMergerVO> checkSubmitInfo(SubmitOrderDTO submitOrderParam, Long userId) {
        ShopCartOrderMergerVO mergerOrder = cacheManagerUtil.getCache(OrderCacheNames.ORDER_CONFIRM_KEY, String.valueOf(userId));
        // 看看订单有没有过期
        if (mergerOrder == null) {
            return ServerResponseEntity.showFailMsg("订单已过期，请重新提交");
        }
        // 防止重复提交
        boolean cad = RedisUtil.cad(OrderCacheNames.ORDER_CONFIRM_UUID_KEY + CacheNames.UNION + userId, String.valueOf(userId));
        if (!cad) {
            return ServerResponseEntity.fail(ResponseEnum.REPEAT_ORDER);
        }
        Integer orderItemNum = 0;
        //获取套餐订单项
        List<ShopCartOrderVO> cartOrders = mergerOrder.getShopCartOrders();
        logger.info("购物车缓存：{}",cartOrders.toString());
        List<ShopCartItemDiscountVO> shopCartItemDiscountVOList = new ArrayList<>();
        Map<Long, Integer> dvyMap = mergerOrder.getDvyTypes().stream().collect(Collectors.toMap(DvyTypeDTO::getShopId, DvyTypeDTO::getDvyType));
        for (ShopCartOrderVO cartOrder : cartOrders) {
            if(Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.SAME_CITY.value())){
                if (Objects.nonNull(cartOrder.getShopCityStatus()) && Objects.equals(cartOrder.getShopCityStatus(), ShopCityStatus.NO_CONFIG.value())) {
                    // 当前店铺未开启同城配送
                    return ServerResponseEntity.showFailMsg("店铺" +cartOrder.getShopName() + "未开启同城配送");
                }
                if (Objects.nonNull(cartOrder.getShopCityStatus()) && cartOrder.getShopCityStatus() < ShopCityStatus.USABLE.value()) {
                    // 超出商家配送距离或起送费不够
                    return ServerResponseEntity.showFailMsg("超出商家"+ cartOrder.getShopName() +"的配送距离或起送费不够");
                }
            }
            // 请选择自提点并填写完整的自提信息
            if(Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.STATION.value())
                    && Objects.isNull(mergerOrder.getStationId()) && Objects.isNull(submitOrderParam.getOrderSelfStationDto())){
                return ServerResponseEntity.showFailMsg("请选择自提点并填写完整的自提信息");
            }
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = cartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                // 超出配送距离
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    if (!shopCartItem.getIsDelivery() && !Objects.equals(dvyMap.get(cartOrder.getShopId()), DeliveryType.STATION.value())) {
                        logger.info("商品不在配送范围且未选择自提");
                        throw new LuckException(ResponseEnum.DELIVERY_OVER);
                    }
                }
                orderItemNum += shopCartItemDiscount.getShopCartItems().size();
                if (Objects.equals(shopCartItemDiscount.getType(), ShopCartItemDiscountType.COMBO.value())){
                    logger.info("套餐商品");
                    cartOrder.setIsHaveComboOrder(true);
                }
            }
        }
        if(Objects.nonNull(mergerOrder.getUserHasScore()) && Objects.nonNull(mergerOrder.getUsableScore())) {
            if (mergerOrder.getUserHasScore() < mergerOrder.getUsableScore()) {
                throw new LuckException(ResponseEnum.NOT_SCORE);
            }
        }
        // 检查下虚拟商品的所需留言是否填写完成
//        if (Objects.equals(mergerOrder.getSpuMold(), 1) && CollectionUtil.isNotEmpty(submitOrderParam.getVirtualRemarkList())) {
        if (CollectionUtil.isNotEmpty(submitOrderParam.getVirtualRemarkList())) {
            List<VirtualRemarkDTO> virtualRemarkList = submitOrderParam.getVirtualRemarkList();
            boolean isRequired = false;
            for (VirtualRemarkVO virtualRemarkVO : mergerOrder.getVirtualRemarkList()) {
                if (virtualRemarkVO.getRequired()) {
                    isRequired = true;
                    break;
                }
            }
            // 如果至少要输入一个备注信息，则不能为空
            if (isRequired && CollectionUtil.isEmpty(virtualRemarkList)) {
                // 不能为空
                return ServerResponseEntity.showFailMsg("备注信息不能为空");
            }
            for (VirtualRemarkDTO virtualRemarkVO : virtualRemarkList) {
                if (virtualRemarkVO.getRequired() && StrUtil.isBlank(virtualRemarkVO.getValue())) {
                    // 不能为空
                    return ServerResponseEntity.showFailMsg("备注信息不能为空");
                }
            }
            mergerOrder.setVirtualRemarkList(mapperFacade.mapAsList(virtualRemarkList,VirtualRemarkVO.class));
        }
        // 处理一下团购订单和秒杀的供应商信息
        handleGroupAndSeckillOrderSupplier(mergerOrder);
        //如果是套餐商品设置订单
        // 设置自提信息
        mergerOrder.setOrderSelfStation(mapperFacade.map(submitOrderParam.getOrderSelfStationDto(), OrderSelfStationVO.class));

        List<OrderShopDTO> orderShopParams = submitOrderParam.getOrderShopParam();

        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        // 检查商品状态
        checkSpuStatus(shopCartOrders);
        List<CouponOrderVO> shopCoupons = new ArrayList<>();
        // 设置备注
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            for (OrderShopDTO orderShopParam : orderShopParams) {
                if (Objects.equals(shopCartOrder.getShopId(), orderShopParam.getShopId())) {
                    shopCartOrder.setRemarks(orderShopParam.getRemarks());
                }
            }
            if (CollUtil.isNotEmpty(shopCartOrder.getCoupons())) {
                for (CouponOrderVO shopCoupon : shopCartOrder.getCoupons()) {
                    if (Objects.equals(Boolean.TRUE, shopCoupon.getChoose())) {
                        shopCoupons.add(shopCoupon);
                    }
                }
            }
        }
        //设置发票
        List<OrderInvoiceDTO> orderInvoiceList = submitOrderParam.getOrderInvoiceList();
        if (CollectionUtil.isNotEmpty(orderInvoiceList)){
            mergerOrder.setOrderInvoiceList(orderInvoiceList);
        }
        logger.info("拆单前：mergerOrder:{}",mergerOrder.toString());
        // 需要拆分订单(订单类型为普通订单才需要拆单)
        if(needSplitShopCartOrder(mergerOrder)){
            // 套餐商品拆单
            splitComboShopCartOrderDto(mergerOrder,userId);
            // 根据供应商拆分订单
            splitShopCartOrderDto(mergerOrder, userId);
            // 根据预售拆分订单
            splitShopCartOrderDtoByPreSale(mergerOrder, userId);
        }
        logger.info("生成订单前：mergerOrder:{}",mergerOrder.toString());
        // 拆单后再生成id
        // 生成订单、订单项和订单地址的id
        loadOrderDateId(userId, mergerOrder, orderItemNum);
        logger.info("生成订单：mergerOrder:{}",mergerOrder.getShopCartOrders());
        // 生成订单id后，再拼接店铺优惠券的订单id列表
        // 优惠券处理
        if (CollUtil.isNotEmpty(shopCoupons)) {
            Map<Long,Set<Long>> orderIdMap = new HashMap<>();

            for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
                Set<Long> orderIds = orderIdMap.get(shopCartOrder.getShopId());
                if (CollUtil.isEmpty(orderIds)) {
                    orderIds = new HashSet<>();
                    orderIdMap.put(shopCartOrder.getShopId(), orderIds);
                }
                orderIds.add(shopCartOrder.getOrderId());
            }

            // 优惠券插入订单id列表
            for (CouponOrderVO shopCoupon : shopCoupons) {
                shopCoupon.setOrderIds(new ArrayList<>(orderIdMap.get(shopCoupon.getShopId())));
            }
        }
        mergerOrder.setShopCoupons(shopCoupons);
        return ServerResponseEntity.success(mergerOrder);
    }

    /**
     * 是否需要拆单
     *
     * 1.套餐需要拆单
     * 2.供应商需要拆单
     * 3.不是定金预售商品，需要拆单
     * @param mergerOrder
     * @return
     */
    private boolean needSplitShopCartOrder(ShopCartOrderMergerVO mergerOrder) {
        // 普通订单才需要拆单
        if (!Objects.equals(mergerOrder.getOrderType().value(), OrderType.ORDINARY.value())){
            return Boolean.FALSE;
        }
        // 如果不是定金预售商品，需要拆分订单
        if(Objects.equals(mergerOrder.getPreSaleType(), PreSaleType.FULLPAY.value())) {
            logger.info("哪里拆了预售");
            return Boolean.TRUE;
        }
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                // 套餐需要拆单
                if (Objects.equals(shopCartItemDiscount.getType(), ShopCartSpuActivityType.COMBO.value())) {
                    logger.info("哪里拆了供应商1");
                    return Boolean.TRUE;
                }
                // 供应商需要拆单
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {

                    // 供应商商品且是供应商发货，需要拆单
                    boolean supplierSplitShopCartOrder = Objects.nonNull(shopCartItem.getSupplierId()) &&
                            !Objects.equals(shopCartItem.getSupplierId(),0L) &&
                            Objects.equals(shopCartItem.getSupplierDeliveryType(),1);
                    if (supplierSplitShopCartOrder) {
                        logger.info("哪里拆了供应商2");
                        return Boolean.TRUE;
                    }
                    // 判断下是否为预售商品,如果是预售商品就拆单
                    if (!Objects.isNull(shopCartItem.getPreSaleType()) && !Objects.equals(shopCartItem.getPreSaleType(),-1)) {
                        logger.info("哪里拆了供应商3");
                        return Boolean.TRUE;
                    }
                }
            }
        }
        return Boolean.FALSE;
    }



    private void splitComboShopCartOrderDto(ShopCartOrderMergerVO mergerOrder,Long userId) {
        List<ShopCartOrderVO> shopCartOrderList = new ArrayList<>();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            boolean recalculate = false;
            int index = 0;
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                // 非套餐项不用处理
                if (!Objects.equals(shopCartItemDiscountDto.getType(), ShopCartSpuActivityType.COMBO.value())) {
                    continue;
                }
                shopCartItemDiscountDto.getChooseComboItemVo().setIndex(index);
                index++;
                // 如果套餐中没有虚拟商品，不用处理
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                boolean isSplit = false;
                while (iterator.hasNext()) {
                    int size = shopCartItemDiscountDto.getShopCartItems().size();
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 不是虚拟商品，不用处理
                    if (Objects.isNull(shopCartItemDto.getSpuMold()) || shopCartItemDto.getSpuMold() != 1) {
                        continue;
                    }
                    if (mergerOrder.getSpuMold() == 0) {
                        logger.info("订单中有虚拟商品，需要拆单");
                        mergerOrder.setSpuMold(1);
                    }
                    // 套餐中的虚拟商品，但只有一个订单项
                    if (Objects.equals(size, 1)) {
                        continue;
                    }
                    ServerResponseEntity<Long> segmentIdResponse = segmentFeignClient.getSegmentIdWithDateTime(DistributedIdKey.MALL4CLOUD_ORDER,userId);
                    ShopCartOrderVO shopCartOrderDto = new ShopCartOrderVO();
                    shopCartOrderDto.setIsHaveComboOrder(shopCartOrder.getIsHaveComboOrder());
                    // 拆分虚拟商品
                    Long orderId = segmentIdResponse.getData();
                    shopCartOrderDto.setShopId(shopCartOrder.getShopId());
                    shopCartOrderDto.setOrderId(orderId);
                    shopCartOrderDto.setShopName(shopCartOrder.getShopName());
                    shopCartOrderDto.setRemarks(shopCartOrder.getRemarks());
                    shopCartOrderDto.setShopCityStatus(shopCartOrder.getShopCityStatus());
                    shopCartOrderDto.setStartDeliveryFee(shopCartOrderDto.getStartDeliveryFee());
                    shopCartOrderDto.setIsRefund(shopCartOrder.getIsRefund());
                    shopCartOrderDto.setOrderType(shopCartOrder.getOrderType());
                    shopCartOrderDto.setShopCartItemDiscounts(new ArrayList<>());
                    shopCartOrderDto.setActualTotal(shopCartOrderDto.getTotal());
                    shopCartOrderDto.setSpuMold(1);
                    SpuVO spuVO = spuFeignClient.getDetailById(shopCartItemDto.getSpuId()).getData();
                    shopCartOrderDto.setWriteOffMultipleCount(spuVO.getWriteOffMultipleCount());
                    shopCartOrderDto.setWriteOffNum(spuVO.getWriteOffNum());
                    shopCartOrderDto.setWriteOffStart(spuVO.getWriteOffStart());
                    shopCartOrderDto.setWriteOffEnd(spuVO.getWriteOffEnd());
                    ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                    shopCartItemDiscount.setChooseComboItemVo(shopCartItemDiscountDto.getChooseComboItemVo());
                    shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                    shopCartOrderDto.getShopCartItemDiscounts().add(shopCartItemDiscount);
                    loadShopCartOrderDto(shopCartOrderDto);
                    shopCartOrderList.add(shopCartOrderDto);
                    // 移除该订单项
                    iterator.remove();
                    if (!isSplit) {
                        isSplit = true;
                    }
                    if (!recalculate) {
                        recalculate = true;
                    }
                }
                // 订单项没有拆分
                if (!isSplit) {
                    continue;
                }
            }
            if (!recalculate) {
                continue;
            }

            loadShopCartOrderDto(shopCartOrder);
        }
        if(CollUtil.isNotEmpty(shopCartOrderList)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrderList);
        }
    }

    private void loadOrderDateId(Long userId, ShopCartOrderMergerVO mergerOrder, Integer orderItemNum) {
        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        List<SegmentItemDTO> segmentItemList = new ArrayList<>();
        segmentItemList.add(new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_ORDER, shopCartOrders.size()));
        segmentItemList.add(new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_ORDER_SETTLEMENT, shopCartOrders.size()));
        segmentItemList.add(new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_ORDER_ITEM, orderItemNum));
        segmentItemList.add(new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_ORDER_ADDR, 1));

        // 获取订单id列表
        ServerResponseEntity<Map<String, List<Long>>> segmentIdResponse = segmentFeignClient.batchSegmentIdWithDateTime(new SegmentDTO(userId, segmentItemList));
        if (segmentIdResponse.isFail()) {
            throw new LuckException(segmentIdResponse.getMsg());
        }
        Map<String, List<Long>> map = segmentIdResponse.getData();
        List<Long> orderIds = map.get(DistributedIdKey.MALL4CLOUD_ORDER);
        List<Long> settlementIds = map.get(DistributedIdKey.MALL4CLOUD_ORDER_SETTLEMENT);
        List<Long> orderItemIds = map.get(DistributedIdKey.MALL4CLOUD_ORDER_ITEM);
        List<Long> addrIds = map.get(DistributedIdKey.MALL4CLOUD_ORDER_ADDR);
        if (CollUtil.isNotEmpty(addrIds) && Objects.nonNull(mergerOrder.getUserAddr())) {
            mergerOrder.getUserAddr().setAddrId(addrIds.get(0));
        }
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            // 设置订单id
            shopCartOrder.setOrderId(orderIds.remove(0));
            shopCartOrder.setSettlementId(settlementIds.remove(0));
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    shopCartItem.setOrderItemId(orderItemIds.remove(0));
                }
            }

        }
    }
    private void splitShopCartOrderDto(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>();
        List<ShopCartOrderVO> normalShopCartOrderList = new ArrayList<>();
        Map<Long, ShopTransFeeVO> supplierIdWithShopTransFeeMap = mergerOrder.getSupplierIdWithShopTransFeeMap();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            // 注意一下等级免运费金额，因为一个店如果免运费，则肯定所以项都免运费了
            long levelFreeTransfee = Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0L : shopCartOrder.getLevelFreeTransfee();
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            long transFee = shopCartOrder.getTransfee();
            Map<Long,ShopCartOrderVO> shopCartOrderMap = new HashMap<>(12);
            List<ShopCartItemVO> normalShopCartItemList = new ArrayList<>();
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                while (iterator.hasNext()) {
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 判断下是否为供应商商品,如果是商家代销供应商商品且为供应商发货才继续

                    if (Objects.equals(shopCartItemDto.getSupplierId(),0L) || !Objects.equals(shopCartItemDto.getSupplierDeliveryType(),1)) {
                        // 普通的商品和商家仓库自己发货的放入同一个list
                        normalShopCartItemList.add(shopCartItemDto);
                        continue;
                    }
                    logger.info("供应商拆单了1~~~~~:{}",shopCartItemDto.toString());
                    ShopCartOrderVO shopCartOrderVO = new ShopCartOrderVO();
                    shopCartOrderVO.setIsHaveComboOrder(shopCartOrder.getIsHaveComboOrder());
                    // 拆分供应商商品
                    if(shopCartOrderMap.containsKey(shopCartItemDto.getSupplierId())){
                        shopCartOrderVO = shopCartOrderMap.get(shopCartItemDto.getSupplierId());
                        ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                        shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                        shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
                    }else {
                        ServerResponseEntity<Long> segmentIdResponse = segmentFeignClient.getSegmentIdWithDateTime(DistributedIdKey.MALL4CLOUD_ORDER,userId);
                        if (!segmentIdResponse.isSuccess()) {
                            throw new LuckException(segmentIdResponse.getMsg());
                        }
                        Long orderId = segmentIdResponse.getData();
                        shopCartOrderVO.setOrderId(orderId);
                        shopCartOrderVO.setShopId(shopCartOrder.getShopId());
                        shopCartOrderVO.setShopName(shopCartOrder.getShopName());
                        shopCartOrderVO.setRemarks(shopCartOrder.getRemarks());
                        shopCartOrderVO.setOrderType(shopCartOrder.getOrderType());
                        shopCartOrderVO.setShopCartItemDiscounts(new ArrayList<>());
                        shopCartOrderVO.setSupplierId(shopCartOrder.getSupplierId());
                        shopCartOrderVO.setSupplierDeliveryType(shopCartOrder.getSupplierDeliveryType());
                        ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                        shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                        shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
                        shopCartOrderMap.put(shopCartItemDto.getSupplierId(),shopCartOrderVO);
                    }
                    // 移除该订单项
                    iterator.remove();
                }
            }
            // 重新算一下供应商
            if(CollectionUtil.isNotEmpty(shopCartOrderMap)) {
                for (Long supplierId : shopCartOrderMap.keySet()) {
                    // 供应商运费放进去
                    if(Objects.nonNull(supplierIdWithShopTransFeeMap)){
                        ShopTransFeeVO shopTransFeeVO = supplierIdWithShopTransFeeMap.get(supplierId);
                        // 店铺订单计算
                        ShopCartOrderVO shopCartOrderVO = shopCartOrderMap.get(supplierId);
                        // 如果有等级免运费金额，则所有都免运费
                        shopCartOrderVO.setTransfee(Objects.isNull(shopTransFeeVO) ? 0L : shopTransFeeVO.getTransfee());
                        shopCartOrderVO.setLevelFreeTransfee(Math.min(levelFreeTransfee,shopCartOrderVO.getTransfee()));
                        loadShopCartOrderDto(shopCartOrderVO);
                        shopCartOrders.add(shopCartOrderVO);
                        transFee = transFee - shopCartOrderVO.getTransfee();
                    }

                }
            }
            // 普通商品和商家仓库发货的供应商商品做一个order
            if(CollectionUtil.isNotEmpty(normalShopCartItemList)){
                ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                shopCartItemDiscount.setShopCartItems(normalShopCartItemList);
                shopCartOrder.setShopCartItemDiscounts(Collections.singletonList(shopCartItemDiscount));
                shopCartOrder.setTransfee(transFee);
                shopCartOrder.setLevelFreeTransfee(Math.min(levelFreeTransfee,shopCartOrder.getTransfee()));
                loadShopCartOrderDto(shopCartOrder);
                normalShopCartOrderList.add(shopCartOrder);
            }
        }
        mergerOrder.setShopCartOrders(new ArrayList<>());
        if(CollectionUtil.isNotEmpty(normalShopCartOrderList)){
            mergerOrder.setShopCartOrders(normalShopCartOrderList);
        }
        if(CollUtil.isNotEmpty(shopCartOrders)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrders);
        }

    }

    private void splitShopCartOrderDtoByPreSale(ShopCartOrderMergerVO mergerOrder, Long userId) {
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>();
        List<ShopCartOrderVO> normalShopCartOrderList = new ArrayList<>();
        Map<Long, ShopTransFeeVO> preSaleTransFeeMap = mergerOrder.getPreSaleTransFeeMap();
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            // 注意一下等级免运费金额，因为一个店如果免运费，则肯定所以项都免运费了
            long levelFreeTransfee = Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0L : shopCartOrder.getLevelFreeTransfee();
            Iterator<ShopCartItemDiscountVO> shopCartIterator = shopCartOrder.getShopCartItemDiscounts().iterator();
            long transFee = shopCartOrder.getTransfee();
            Map<Long,ShopCartOrderVO> shopCartOrderMap = new HashMap<>(12);
            List<ShopCartItemVO> normalShopCartItemList = new ArrayList<>();
            while (shopCartIterator.hasNext()) {
                ShopCartItemDiscountVO shopCartItemDiscountDto = shopCartIterator.next();
                Iterator<ShopCartItemVO> iterator = shopCartItemDiscountDto.getShopCartItems().iterator();
                while (iterator.hasNext()) {
                    ShopCartItemVO shopCartItemDto = iterator.next();
                    // 判断下是否为预售商品,如果是预售商品就拆单
                    if (Objects.isNull(shopCartItemDto.getPreSaleType()) || Objects.equals(shopCartItemDto.getPreSaleType(),-1)) {
                        // 普通的商品放入同一个list
                        normalShopCartItemList.add(shopCartItemDto);
                        continue;
                    }


                    ShopCartOrderVO shopCartOrderVO = new ShopCartOrderVO();
                    // 拆分预售商品
                    logger.info("开始拆分预售商品...............");
                    ServerResponseEntity<Long> segmentIdResponse = segmentFeignClient.getSegmentIdWithDateTime(DistributedIdKey.MALL4CLOUD_ORDER,userId);
                    if (!segmentIdResponse.isSuccess()) {
                        throw new LuckException(segmentIdResponse.getMsg());
                    }
                    Long orderId = segmentIdResponse.getData();
                    shopCartOrderVO.setOrderId(orderId);
                    shopCartOrderVO.setShopId(shopCartOrder.getShopId());
                    shopCartOrderVO.setShopName(shopCartOrder.getShopName());
                    shopCartOrderVO.setRemarks(shopCartOrder.getRemarks());
                    shopCartOrderVO.setOrderType(shopCartOrder.getOrderType());
                    shopCartOrderVO.setShopCartItemDiscounts(new ArrayList<>());
                    shopCartOrderVO.setSupplierId(shopCartOrder.getSupplierId());
                    shopCartOrderVO.setSupplierDeliveryType(shopCartOrder.getSupplierDeliveryType());
                    ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                    shopCartItemDiscount.setShopCartItems(Collections.singletonList(shopCartItemDto));
                    shopCartOrderVO.getShopCartItemDiscounts().add(shopCartItemDiscount);
                    shopCartOrderMap.put(shopCartItemDto.getSkuId(),shopCartOrderVO);
                    // 移除该订单项
                    iterator.remove();
                }
            }
            // 重新算一下预售商品
            if(CollectionUtil.isNotEmpty(shopCartOrderMap)) {
                logger.info("重新算一下预售商品..............."+shopCartOrderMap.toString());
                for (Long skuId : shopCartOrderMap.keySet()) {
                    // 运费放进去
                    if(CollectionUtil.isEmpty(preSaleTransFeeMap)){ //TODO 张征 如果是预售认养的虚拟商品怎么运费都是0
                        // 店铺订单计算
                        ShopCartOrderVO shopCartOrderVO = shopCartOrderMap.get(skuId);
                        // 如果有等级免运费金额，则所有都免运费
                        shopCartOrderVO.setTransfee(0L);
                        shopCartOrderVO.setLevelFreeTransfee(Math.min(levelFreeTransfee,shopCartOrderVO.getTransfee()));
                        shopCartOrderVO.setIsHaveComboOrder(shopCartOrder.getIsHaveComboOrder());
                        loadShopCartOrderDto(shopCartOrderVO);
                        shopCartOrders.add(shopCartOrderVO);
                        transFee = transFee - shopCartOrderVO.getTransfee();
                    }else{
                        ShopTransFeeVO shopTransFeeVO = preSaleTransFeeMap.get(skuId);
                        // 店铺订单计算
                        ShopCartOrderVO shopCartOrderVO = shopCartOrderMap.get(skuId);
                        // 如果有等级免运费金额，则所有都免运费
                        shopCartOrderVO.setTransfee(Objects.isNull(shopTransFeeVO) ? 0L : shopTransFeeVO.getTransfee());
                        shopCartOrderVO.setLevelFreeTransfee(Math.min(levelFreeTransfee,shopCartOrderVO.getTransfee()));
                        shopCartOrderVO.setIsHaveComboOrder(shopCartOrder.getIsHaveComboOrder());
                        loadShopCartOrderDto(shopCartOrderVO);
                        shopCartOrders.add(shopCartOrderVO);
                        transFee = transFee - shopCartOrderVO.getTransfee();
                    }


                }
            }
            // 普通商品和商家仓库发货的供应商商品做一个order
            if(CollectionUtil.isNotEmpty(normalShopCartItemList)){
                logger.info("普通商品和商家仓库发货的供应商商品做一个order...............");
                ShopCartItemDiscountVO shopCartItemDiscount = new ShopCartItemDiscountVO();
                shopCartItemDiscount.setShopCartItems(normalShopCartItemList);
                shopCartOrder.setShopCartItemDiscounts(Collections.singletonList(shopCartItemDiscount));
                shopCartOrder.setTransfee(transFee);
                shopCartOrder.setLevelFreeTransfee(Math.min(levelFreeTransfee,shopCartOrder.getTransfee()));
                loadShopCartOrderDto(shopCartOrder);
                normalShopCartOrderList.add(shopCartOrder);
            }
        }
        mergerOrder.setShopCartOrders(new ArrayList<>());
        if(CollectionUtil.isNotEmpty(normalShopCartOrderList)){
            mergerOrder.setShopCartOrders(normalShopCartOrderList);
        }
        if(CollUtil.isNotEmpty(shopCartOrders)) {
            mergerOrder.getShopCartOrders().addAll(shopCartOrders);
        }
    }

    private void loadShopCartOrderDto(ShopCartOrderVO shopCartOrderVO) {
        if(Objects.isNull(shopCartOrderVO.getLevelFreeTransfee())) {
            shopCartOrderVO.setLevelFreeTransfee(0L);
        }
        if(Objects.isNull(shopCartOrderVO.getTransfee())) {
            shopCartOrderVO.setTransfee(0L);
        }
        shopCartOrderVO.setUseScore(0L);
        shopCartOrderVO.setActualTotal(shopCartOrderVO.getTransfee() - shopCartOrderVO.getLevelFreeTransfee());
        shopCartOrderVO.setTotal(0L);
        shopCartOrderVO.setTotalCount(0);
        shopCartOrderVO.setDiscountReduce(0L);
        shopCartOrderVO.setCouponReduce(0L);
        shopCartOrderVO.setPlatformCouponReduce(0L);
        shopCartOrderVO.setScoreReduce(0L);
        shopCartOrderVO.setPlatformAmount(shopCartOrderVO.getLevelFreeTransfee());
        shopCartOrderVO.setLevelReduce(0L);
        shopCartOrderVO.setShopReduce(shopCartOrderVO.getPlatformAmount());
        shopCartOrderVO.setPlatformCommission(0L);
        shopCartOrderVO.setTotalPurchasePlatformCommission(0L);
        boolean userCoupon = false;
        List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrderVO.getShopCartItemDiscounts();
        for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
            for (ShopCartItemVO cartItemDto : shopCartItemDiscount.getShopCartItems()) {
                // 订单项的金额在生成订单时已经算好了，这里只需要相加即可，不需要别的处理
                shopCartOrderVO.setActualTotal(shopCartOrderVO.getActualTotal() + cartItemDto.getActualTotal());
                shopCartOrderVO.setTotal(shopCartOrderVO.getTotal() + cartItemDto.getTotalAmount());
                shopCartOrderVO.setTotalCount(shopCartOrderVO.getTotalCount() + cartItemDto.getCount());
                shopCartOrderVO.setShopReduce(shopCartOrderVO.getShopReduce() + cartItemDto.getShareReduce());
                if (Objects.nonNull(cartItemDto.getComboAmount())){
                    //加上套餐优惠金额
                    shopCartOrderVO.setShopReduce(shopCartOrderVO.getShopReduce() + cartItemDto.getComboAmount());
                }
                cartItemDto.setPlatformCommission(Objects.isNull(cartItemDto.getPlatformCommission()) ? 0L : cartItemDto.getPlatformCommission());
                shopCartOrderVO.setPlatformCommission(shopCartOrderVO.getPlatformCommission() + cartItemDto.getPlatformCommission());
                shopCartOrderVO.setSupplierId(cartItemDto.getSupplierId());
                shopCartOrderVO.setSupplierDeliveryType(cartItemDto.getSupplierDeliveryType());
                shopCartOrderVO.setPreSaleType(cartItemDto.getPreSaleType());
                if(Objects.nonNull(cartItemDto.getPurchasePlatformCommission())) {
                    shopCartOrderVO.setTotalPurchasePlatformCommission(shopCartOrderVO.getTotalPurchasePlatformCommission() + cartItemDto.getPurchasePlatformCommission());
                }
                if(Objects.nonNull(cartItemDto.getDiscountAmount())) {
                    shopCartOrderVO.setDiscountReduce(shopCartOrderVO.getDiscountReduce() + cartItemDto.getDiscountAmount());
                }
                if(Objects.nonNull(cartItemDto.getShopCouponAmount())) {
                    shopCartOrderVO.setCouponReduce(shopCartOrderVO.getCouponReduce() + cartItemDto.getShopCouponAmount());
                    userCoupon = true;
                }
                if(Objects.nonNull(cartItemDto.getPlatformCouponAmount())) {
                    shopCartOrderVO.setPlatformCouponReduce(shopCartOrderVO.getPlatformCouponReduce() + cartItemDto.getPlatformCouponAmount());
                }
                if(Objects.nonNull(cartItemDto.getScoreReduce())) {
                    shopCartOrderVO.setScoreReduce(shopCartOrderVO.getScoreReduce() + cartItemDto.getScoreReduce());
                }
                if(Objects.nonNull(cartItemDto.getPlatformShareReduce())) {
                    shopCartOrderVO.setPlatformAmount(shopCartOrderVO.getPlatformAmount() + cartItemDto.getPlatformShareReduce());
                }
                if(Objects.nonNull(cartItemDto.getLevelReduce())) {
                    shopCartOrderVO.setLevelReduce(shopCartOrderVO.getLevelReduce() + cartItemDto.getLevelReduce());
                }
                if(Objects.nonNull(cartItemDto.getScorePrice())) {
                    shopCartOrderVO.setUseScore(shopCartOrderVO.getUseScore() + cartItemDto.getScorePrice());
                }
            }
        }
    }

    public void tryLockStock(List<ShopCartOrderVO> shopCartOrders) {

        List<SkuStockLockDTO> skuStockLocks = new ArrayList<>();

        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {

            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                for (ShopCartItemVO orderItem : shopCartItems) {
                    logger.info("1是供应商发货了.........."+orderItem.getSupplierId());
                    //供应商
                    if (!Objects.equals(orderItem.getSupplierId(),0L) && Objects.equals(orderItem.getSupplierDeliveryType(),1)) {
                        logger.info("2供应商发货了.........."+orderItem.getSupplierSpuId());
                        skuStockLocks.add(new SkuStockLockDTO(orderItem.getShopId(), orderItem.getSupplierSpuId(), orderItem.getSupplierSkuId(), shopCartOrder.getOrderId(), orderItem.getCount(), -1,orderItem.getSpuId()));
                        continue;
                    }
                    skuStockLocks.add(new SkuStockLockDTO(orderItem.getShopId(), orderItem.getSpuId(), orderItem.getSkuId(), shopCartOrder.getOrderId(), orderItem.getCount(), -1,null));
                    //处理赠品订单项
                    GiveawayVO giveaway = orderItem.getGiveaway();
                    if (Objects.isNull(giveaway)) {
                        continue;
                    }
                    // 赠品库存计算
                    for (GiveawaySpuVO giveawaySpuVO : giveaway.getGiveawaySpus()) {
                        skuStockLocks.add(new SkuStockLockDTO(giveawaySpuVO.getShopId(),giveawaySpuVO.getSpuId(), giveawaySpuVO.getSkuId(), shopCartOrder.getOrderId(), giveawaySpuVO.getGiveawayNum(), -1, null));
                    }
                }
            }
        }
        logger.info("3供应商发货了.........."+skuStockLocks.size());
        // 锁定库存
        ServerResponseEntity<?> lockStockResponse = skuStockLockFeignClient.lock(skuStockLocks);
        // 提示具体哪个商品库存不足
        if (Objects.equals(ResponseEnum.NOT_STOCK.value(), lockStockResponse.getCode())) {
            for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
                List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
                for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                    List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                    for (ShopCartItemVO orderItem : shopCartItems) {
                        boolean flag = Objects.nonNull(orderItem.getSupplierSkuId()) && Objects.equals(orderItem.getSupplierSkuId().toString(),
                                lockStockResponse.getData().toString());
                        if (Objects.equals(orderItem.getSkuId().toString(), lockStockResponse.getData().toString()) || flag){
                            OrderLangUtil.shopCartItemLang(orderItem);
                            String skuName = Objects.isNull(orderItem.getSkuName()) ? "": orderItem.getSkuName();
                            throw new LuckException(orderItem.getSpuName() + " " + skuName + " 库存不足");
                        }
                    }
                }
            }
        }
        if (!lockStockResponse.isSuccess()) {
            throw new LuckException(lockStockResponse);
        }
    }

    public void tryLockCoupon(ShopCartOrderMergerVO mergerOrder) {
        List<LockCouponDTO> lockCouponParams;
        List<Long> orderIds = new ArrayList<>();
        // 如果不为空表示拆分过订单
        if(CollectionUtil.isEmpty(mergerOrder.getShopCoupons())) {
            List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
            for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
                Long orderId = shopCartOrder.getOrderId();
                List<CouponOrderVO> coupons = shopCartOrder.getCoupons();
                if (CollectionUtil.isNotEmpty(coupons)) {
                    for (CouponOrderVO coupon : coupons) {
                        if (Objects.equals(Boolean.TRUE, coupon.getChoose())) {
                            coupon.setOrderId(orderId);
                        }
                    }
                }
                orderIds.add(orderId);
            }
            // 锁优惠券
            lockCouponParams = getLockCouponDto(mergerOrder, orderIds);
        }else {
            for (CouponOrderVO shopCoupon : mergerOrder.getShopCoupons()) {
                orderIds.addAll(shopCoupon.getOrderIds());
            }
            // 锁定优惠券
            // 平台优惠券
            lockCouponParams = new ArrayList<>();
            LockCouponDTO platformLockCouponParam = getLockCouponDTO(mergerOrder.getCoupons());
            if (platformLockCouponParam != null) {
                // 平台优惠券涉及多个订单，所以设置订单id为多个订单id以逗号分割
                platformLockCouponParam.setOrderIds(StrUtil.join(StrUtil.COMMA, orderIds));
                lockCouponParams.add(platformLockCouponParam);
            }
            // 店铺优惠券
            LockCouponDTO shopLockCouponParam = getLockCouponDTO(mergerOrder.getShopCoupons());
            if (shopLockCouponParam != null) {
                lockCouponParams.add(shopLockCouponParam);
            }
        }
        if (CollectionUtil.isNotEmpty(lockCouponParams)) {
            ServerResponseEntity<Void> lockCouponResponse = couponOrderFeignClient.lockCoupon(lockCouponParams);
            if (!lockCouponResponse.isSuccess()) {
                throw new LuckException(lockCouponResponse.getMsg());
            }
        }
    }

    /**
     * 尝试锁定优惠券
     * @param mergerOrder
     * @param orderIds
     */
    private List<LockCouponDTO> getLockCouponDto(ShopCartOrderMergerVO mergerOrder, List<Long> orderIds) {
        // 锁定优惠券
        // 平台优惠券
        List<LockCouponDTO> lockCouponParams = new ArrayList<>();
        LockCouponDTO platformLockCouponParam = getLockCouponDTO(mergerOrder.getCoupons());
        if (platformLockCouponParam != null) {
            // 平台优惠券涉及多个订单，所以设置订单id为多个订单id以逗号分割
            platformLockCouponParam.setOrderIds(StrUtil.join(StrUtil.COMMA, orderIds));
            lockCouponParams.add(platformLockCouponParam);
        }
        // 店铺优惠券
        for (ShopCartOrderVO shopCartOrder : mergerOrder.getShopCartOrders()) {
            LockCouponDTO shopLockCouponParam = getLockCouponDTO(shopCartOrder.getCoupons());
            if (shopLockCouponParam != null) {
                lockCouponParams.add(shopLockCouponParam);
            }
        }

        return lockCouponParams;
    }

    private LockCouponDTO getLockCouponDTO(List<CouponOrderVO> couponOrders) {
        if (CollectionUtil.isEmpty(couponOrders)) {
            return null;
        }
        for (CouponOrderVO couponOrder : couponOrders) {
            if ((Objects.equals(Boolean.TRUE, couponOrder.getChoose())) && couponOrder.getCanUse()) {
                LockCouponDTO param = new LockCouponDTO();
                if(Objects.nonNull(couponOrder.getOrderId())) {
                    param.setOrderIds(String.valueOf(couponOrder.getOrderId()));
                }else{
                    param.setOrderIds(StrUtil.join(StrUtil.COMMA,couponOrder.getOrderIds()));
                }
                param.setCouponId(couponOrder.getCouponId());
                param.setCouponUserId(couponOrder.getCouponUserId());
                param.setReduceAmount(couponOrder.getReduceAmount());
                return param;
            }
        }
        return null;
    }

    public void tryLockScore(ShopCartOrderMergerVO mergerOrder) {
        // 如果没有使用积分，就不用锁定积分啦
        if (Objects.isNull(mergerOrder.getUsableScore()) || Objects.equals(mergerOrder.getUsableScore(), 0L)) {
            logger.info("没有使用积分，不用锁定积分");
            return;
        }
        List<ShopCartOrderVO> shopCartOrders = mergerOrder.getShopCartOrders();
        List<UserScoreLockDTO> userScoreLocks = new ArrayList<>();
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            if (Objects.equals(shopCartOrder.getUseScore(), 0L)) {
                continue;
            }
            userScoreLocks.add(new UserScoreLockDTO(shopCartOrder.getOrderId(), shopCartOrder.getUseScore(), mergerOrder.getOrderType().value()));
        }

        // 锁定积分
        ServerResponseEntity<Void> scoreResp = userScoreLockFeignClient.lock(userScoreLocks);
        if (!scoreResp.isSuccess()) {
            logger.info("锁定积分失败，失败原因：{}", scoreResp.getMsg());
            throw new LuckException(scoreResp.getMsg());
        }

    }

    private void checkSpuStatus(List<ShopCartOrderVO> shopCartOrders) {
        List<Long> spuIds = new ArrayList<>();
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
            List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                for (ShopCartItemVO orderItem : shopCartItems) {
                    spuIds.add(orderItem.getSpuId());
                }
            }
        }
        if (CollUtil.isNotEmpty(spuIds)) {
            ServerResponseEntity<?> skuStatusResponseEntity = searchSpuFeignClient.checkSpuStatus(spuIds);
            if (Objects.equals(skuStatusResponseEntity.getCode(), ResponseEnum.SPU_STATUS_ERROR.value())) {
                for (ShopCartOrderVO shopCartOrder : shopCartOrders) {
                    List<ShopCartItemDiscountVO> shopCartItemDiscounts = shopCartOrder.getShopCartItemDiscounts();
                    for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
                        List<ShopCartItemVO> shopCartItems = shopCartItemDiscount.getShopCartItems();
                        for (ShopCartItemVO orderItem : shopCartItems) {
                            if (Objects.equals(orderItem.getSpuId().toString(), skuStatusResponseEntity.getData().toString())) {
                                OrderLangUtil.shopCartItemLang(orderItem);
                                String skuName = Objects.isNull(orderItem.getSkuName()) ? "": orderItem.getSkuName();
                                throw new LuckException(orderItem.getSpuName() + " " + skuName + " 不在正常状态");
                            }
                        }
                    }
                }
            }
            if (!skuStatusResponseEntity.isSuccess()) {
                throw new LuckException(skuStatusResponseEntity);
            }
        }
    }

    private void handleGroupAndSeckillOrderSupplier(ShopCartOrderMergerVO mergerOrder){
        if (Objects.equals(mergerOrder.getOrderType().value(), OrderType.GROUP.value()) ||
                Objects.equals(mergerOrder.getOrderType().value(), OrderType.SECKILL.value())) {
            logger.info("团购订单或秒杀订单，处理供应商信息");
            // 如果是团购订单，需要处理一下供应商商品信息
            mergerOrder.getShopCartOrders().forEach(shopCartOrderVO -> {
                shopCartOrderVO.getShopCartItemDiscounts().forEach(shopCartItemDiscountVO -> {
                    shopCartItemDiscountVO.getShopCartItems().forEach(shopCartItemVO -> {
                        shopCartOrderVO.setSupplierDeliveryType(shopCartItemVO.getSupplierDeliveryType());
                        shopCartOrderVO.setSupplierId(shopCartItemVO.getSupplierId());
                    });
                });
            });
        }
    }
}
